package com.jack.leetcode.eachProblem06;

public class 二进制求和 {

    public static void main(String[] args) {
        System.out.println(addBinary("1010", "1011"));
        System.out.println(addBinary("11", "1"));
    }

    public static String addBinary(String a, String b) {
        StringBuilder result = new StringBuilder();
        int m = a.length();
        int n = b.length();
        if (a.length() < b.length()) {
            m = b.length();
            n = a.length();
            String tmp = a;
            a = b;
            b = tmp;
        }
        boolean increse = false;
        int j = n - 1;
        for (int i = m - 1; i >= 0; i--) {
            if (j >= 0) {
                if (a.charAt(i) == b.charAt(j) && a.charAt(i) == '1') {
                    if (increse) {
                        result.append('1');
                    } else {
                        result.append('0');
                    }
                    increse = true;
                    j--;
                    continue;
                }
                if (a.charAt(i) == b.charAt(j) && a.charAt(i) == '0') {
                    if (increse) {
                        result.append('1');
                    } else {
                        result.append('0');
                    }
                    increse = false;
                    j--;
                    continue;
                }
                if (increse) {
                    result.append('0');
                    increse = true;
                } else {
                    result.append('1');
                    increse = false;
                }
                j--;
                continue;
            }
            if (increse && a.charAt(i) == '1') {
                result.append('0');
                increse = true;
                continue;
            }
            if (increse && a.charAt(i) == '0') {
                result.append('1');
                increse = false;
                continue;
            }
            result.append(a.charAt(i));
            increse = false;
        }
        if (increse) {
            result.append('1');
        }
        return result.reverse().toString();
    }
}
